﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using ServiceBus.Contract;

namespace ServiceBus.Service
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class MessageSender : IMessageSender
    {
        IMessageSenderCallBack _CallBack;
        public MessageSender()
        {
        }
        private string ServiceName = string.Empty;
        public void Init(string address)
        {
            this.ServiceName = address;
            this._CallBack = OperationContext.Current.GetCallbackChannel<IMessageSenderCallBack>();
            EventEngine.MessageSending += new EventHandler<Message>(Tool_MessageSending);
            EventEngine.HeartBeatEvent += new EventHandler(Tool_HeartBeatEvent);
        }

        void Tool_HeartBeatEvent(object sender, EventArgs e)
        {
            try
            {
                this._CallBack.SendHeartBeat(this.ServiceName);
            }
            catch (Exception ex)
            {
                if ((ex as System.ServiceModel.CommunicationObjectAbortedException) != null)
                {
                    EventEngine.HeartBeatEvent -= this.Tool_HeartBeatEvent;
                }
            }
        }

        void Tool_MessageSending(object sender, Message e)
        {
            try
            {
                e.ServiceName = this.ServiceName;
                this._CallBack.SendMessage(e);
            }
            catch (Exception ex)
            {
                if ((ex as System.ServiceModel.CommunicationObjectAbortedException) != null)
                {
                    EventEngine.MessageSending -= this.Tool_MessageSending;
                }
            }
        }
      
    }
}